package zld369504.tw.m_team;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import zld369504.tw.m_team.api.MTeamHttpsApi;
import zld369504.tw.m_team.api.MTeamHttpsApiImpl;
import zld369504.tw.m_team.dao.CombinedResults;
import zld369504.tw.m_team.dao.Torrent;
import zld369504.tw.m_team.dao.TorrentDetail;
import zld369504.tw.m_team.exception.MyException;
import zld369504.tw.m_team.fragments.TorrentBasicInfoFragment;
import zld369504.tw.m_team.fragments.TorrentDMMFragment;
import zld369504.tw.m_team.fragments.TorrentDescriptionFragment;
import zld369504.tw.m_team.fragments.TorrentIMDbFragment;

public class TorrentDetailActivity extends BaseActivity {

    private Toolbar toolbar;
    private Torrent torrent;

    private boolean isAdult;

    private TabLayout tabLayout;
    private ViewPager viewPager;
    private FragmentViewPagerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_torrent_detail);
        torrent = (Torrent) getIntent().getSerializableExtra("torrent");
        isAdult = getIntent().getBooleanExtra("isAdult", false);
        setupToolBar();

        getTorrentDetail(torrent.getTorrentId());
    }

    private void setupToolBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setSubtitle(torrent.getTitle());
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    private void setupView(List<Integer> titleList, List<Fragment> fragmentList) {
        tabLayout = findViewById(R.id.tabLayout);
        tabLayout.setVisibility(View.VISIBLE);
        tabLayout.setTabTextColors(getResources().getColor(android.R.color.white), getResources().getColor(android.R.color.white));
        viewPager = findViewById(R.id.viewPager);
        viewPager.setOffscreenPageLimit(3);
        adapter = new FragmentViewPagerAdapter(getSupportFragmentManager(),
                titleList,
                fragmentList,
                this);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    private void getTorrentDetail(final int torrentId) {
        Flowable.create(new FlowableOnSubscribe<String>() {
            @Override
            public void subscribe(final FlowableEmitter<String> emitter) throws Exception {
                Callback callback = new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        emitter.onError(e);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        int responseCode = response.code();
                        if (responseCode == 200) {
                            String body = response.body().string();
                            emitter.onNext(body);
                        } else if (responseCode == 302) {
                            String location = response.header("Location");
                            // TODO: 2018/1/11 login ? -> login activity
                            emitter.onError(new MyException("302", location));
                        }
                    }
                };
                MTeamHttpsApi api = MTeamHttpsApiImpl.getInstance();
                api.getTorrentDetailInfo(torrentId, callback);
            }
        }, BackpressureStrategy.DROP)
                .subscribeOn(Schedulers.io())
                .map(new Function<String, TorrentDetail>() {
                    @Override
                    public TorrentDetail apply(String s) throws Exception {
                        return DataParser.parseTorrentDetail(s, isAdult);
                    }
                })
                .map(new Function<TorrentDetail, CombinedResults>() {
                    @Override
                    public CombinedResults apply(TorrentDetail detail) throws Exception {
                        final List<Fragment> fragmentList = new ArrayList<>();
                        final List<Integer> titleList = new ArrayList<>();

                        fragmentList.add(TorrentDescriptionFragment.getInstance(detail));
                        titleList.add(R.string.torrent_detail_description);

                        fragmentList.add(TorrentBasicInfoFragment.getInstance(detail));
                        titleList.add(R.string.torrent_detail_basic_info);

                        //IMDb
                        if (!TextUtils.isEmpty(detail.getImdbInfo())) {
                            fragmentList.add(TorrentIMDbFragment.getInstance(detail));
                            titleList.add(R.string.torrent_detail_imdb);
                        }

                        if (detail.isAdult()) {
                            if (detail.getDmmInfo() != null) {
                                fragmentList.add(TorrentDMMFragment.getInstance(detail.getDmmInfo()));
                                titleList.add(R.string.torrent_detail_dmm);
                            }
                        }
                        CombinedResults results = new CombinedResults();
                        results.fragmentList = fragmentList;
                        results.titleList = titleList;
                        return results;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<CombinedResults>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        s.request(1);
                    }

                    @Override
                    public void onNext(CombinedResults detail) {
                        setupView(detail.titleList, detail.fragmentList);
                    }

                    @Override
                    public void onError(Throwable t) {
                        showErrorDialog("请求出错" + t.toString());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
